<!-- src/views/PublishPostView.vue -->
<template>
    <div class="publish-container">
      <AppNavbar />

      <div class="publish-form-container">
        <h1>发布新帖子</h1>

        <form @submit.prevent="submitPost" class="publish-form">
          <!-- 帖子类型选择 -->
          <div class="form-group">
            <label for="categoryId">帖子类型 *</label>
            <select
              id="categoryId"
              v-model="postForm.categoryId"
              class="form-control"
              required
            >
              <option value="" disabled selected>请选择帖子类型</option>
              <option
                v-for="category in categoryList"
                :key="category.categoryId"
                :value="category.categoryId"
              >
                {{ category.categoryName }}
              </option>
            </select>
          </div>

          <!-- 帖子标题 -->
          <div class="form-group">
            <label for="title">帖子标题 *</label>
            <input
              type="text"
              id="title"
              v-model="postForm.title"
              class="form-control"
              placeholder="请输入帖子标题"
              required
            />
          </div>

          <!-- 帖子内容 -->
          <div class="form-group">
            <label for="content">帖子内容 *</label>
            <textarea
              id="content"
              v-model="postForm.content"
              class="form-control content-textarea"
              placeholder="请输入帖子内容"
              required
            ></textarea>
          </div>

          <!-- 附件上传 -->
          <div class="form-group">
            <label>附件上传</label>
            <div class="file-upload-area">
              <input
                type="file"
                ref="fileInput"
                @change="handleFileUpload"
                class="file-input"
                multiple
              />
              <div class="file-upload-placeholder" @click="triggerFileInput">
                <i class="iconfont icon-add"></i>
                <p>点击选择文件</p>
              </div>
            </div>

            <!-- 已上传文件列表 -->
            <div v-if="uploadedFiles.length > 0" class="uploaded-files">
              <div
                v-for="(file, index) in uploadedFiles"
                :key="index"
                class="uploaded-file-item"
              >
                <!-- 图片预览 -->
                <div v-if="file.isImage" class="file-preview">
                  <img :src="file.previewUrl" :alt="file.name" class="preview-image" />
                </div>

                <span class="file-name">{{ file.name }}</span>
                <span class="file-status">{{ file.status }}</span>
                <button
                  type="button"
                  @click="removeFile(index)"
                  class="remove-file-btn"
                >
                  删除
                </button>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="form-actions">
            <button type="button" @click="goBack" class="cancel-btn">取消</button>
            <button type="submit" :disabled="isSubmitting" class="submit-btn">
              {{ isSubmitting ? '发布中...' : '发布帖子' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import AppNavbar from '../components/AppNavbar.vue'
import apiClient from '../utils/api.js'

export default {
  name: 'PublishPostView',
  components: {
    AppNavbar
  },
  setup () {
    const router = useRouter()
    const categoryList = ref([])
    const postForm = ref({
      categoryId: '',
      title: '',
      content: ''
    })
    const uploadedFiles = ref([])
    const fileInput = ref(null)
    const isSubmitting = ref(false)

    onMounted(() => {
      fetchCategoryList()
    })

    const fetchCategoryList = async () => {
      try {
        // 首先尝试从localStorage获取
        const cachedCategories = localStorage.getItem('categoryList')
        if (cachedCategories) {
          categoryList.value = JSON.parse(cachedCategories)
        }

        // 然后从服务器获取最新数据
        const response = await apiClient.get('/community/getCategoryList')
        if (response.data.code === '200') {
          categoryList.value = response.data.data
          // 更新localStorage
          localStorage.setItem('categoryList', JSON.stringify(response.data.data))
        } else {
          console.error('获取帖子类型列表失败:', response.data.msg)
        }
      } catch (error) {
        console.error('请求帖子类型列表出错:', error)
      }
    }

    const triggerFileInput = () => {
      fileInput.value.click()
    }

    const handleFileUpload = async (event) => {
      const files = Array.from(event.target.files)

      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        const isImage = file.type.startsWith('image/')

        const fileRecord = {
          name: file.name,
          status: '上传中...',
          url: null,
          isImage,
          previewUrl: null
        }

        // 如果是图片，生成预览
        if (isImage) {
          const previewUrl = URL.createObjectURL(file)
          fileRecord.previewUrl = previewUrl
        }

        // 将文件记录添加到列表中
        const fileIndex = uploadedFiles.value.length
        uploadedFiles.value.push(fileRecord)

        try {
          // 上传文件
          const formData = new FormData()
          formData.append('file', file)

          const response = await apiClient.put('/community/uploadAttachment', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })

          if (response.data.code === '200') {
            // 上传成功后立即更新状态和URL
            uploadedFiles.value[fileIndex].status = '已上传'
            uploadedFiles.value[fileIndex].url = response.data.data
          } else {
            uploadedFiles.value[fileIndex].status = '上传失败'
            console.error('文件上传失败:', response.data.msg)
          }
        } catch (error) {
          uploadedFiles.value[fileIndex].status = '上传失败'
          console.error('文件上传出错:', error)
        }
      }

      // 清空input，以便可以重复选择相同文件
      event.target.value = ''
    }

    const removeFile = (index) => {
      const file = uploadedFiles.value[index]
      // 如果有预览URL，释放它
      if (file.previewUrl) {
        URL.revokeObjectURL(file.previewUrl)
      }
      uploadedFiles.value.splice(index, 1)
    }

    const submitPost = async () => {
      if (!postForm.value.categoryId || !postForm.value.title || !postForm.value.content) {
        alert('请填写所有必填项')
        return
      }

      isSubmitting.value = true

      try {
        const postData = {
          categoryId: parseInt(postForm.value.categoryId),
          title: postForm.value.title,
          content: postForm.value.content
        }

        // 如果有上传的文件，添加附件路径列表
        const uploadedFileUrls = uploadedFiles.value
          .filter(file => file.url)
          .map(file => file.url)

        if (uploadedFileUrls.length > 0) {
          postData.attachmentPathList = uploadedFileUrls
        }

        const response = await apiClient.post('/community/addPost', postData)

        if (response.data.code === '200') {
          alert('帖子发布成功！')
          router.push({ name: 'Community' })
        } else {
          alert('发布失败: ' + response.data.msg)
        }
      } catch (error) {
        console.error('发布帖子出错:', error)
        alert('发布帖子时发生错误')
      } finally {
        isSubmitting.value = false
      }
    }

    const goBack = () => {
      router.go(-1)
    }

    return {
      categoryList,
      postForm,
      uploadedFiles,
      fileInput,
      isSubmitting,
      triggerFileInput,
      handleFileUpload,
      removeFile,
      submitPost,
      goBack
    }
  }
}
</script>

  <style scoped>
  @import '//at.alicdn.com/t/c/font_5004955_4kt128cmqdu.css';

  .publish-container {
    background: linear-gradient(to right, #e0f7fa, #ffffff);
    min-height: 100vh;
    padding: 20px;
  }

  .publish-form-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 30px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }

  .publish-form-container h1 {
    color: #1890ff;
    text-align: center;
    margin-bottom: 30px;
  }

  .form-group {
    margin-bottom: 20px;
  }

  .form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #333;
  }

  .form-control {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    font-size: 14px;
    transition: all 0.3s;
    box-sizing: border-box;
  }

  .form-control:focus {
    border-color: #1890ff;
    outline: 0;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  }

  .content-textarea {
    min-height: 200px;
    resize: vertical;
  }

  .file-upload-area {
    position: relative;
  }

  .file-input {
    display: none;
  }

  .file-upload-placeholder {
    border: 2px dashed #d9d9d9;
    border-radius: 4px;
    padding: 30px;
    text-align: center;
    cursor: pointer;
    transition: border-color 0.3s;
  }

  .file-upload-placeholder:hover {
    border-color: #1890ff;
  }

  .file-upload-placeholder .iconfont {
    font-size: 32px;
    color: #1890ff;
  }

  .file-upload-placeholder p {
    margin: 10px 0 0;
    color: #666;
  }

  .uploaded-files {
    margin-top: 15px;
  }

  .uploaded-file-item {
    display: flex;
    align-items: center;
    padding: 10px;
    background-color: #f5f5f5;
    border-radius: 4px;
    margin-bottom: 10px;
  }

  .file-preview {
    margin-right: 10px;
  }

  .preview-image {
    max-width: 60px;
    max-height: 60px;
    object-fit: cover;
    border-radius: 4px;
  }

  .file-name {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .file-status {
    color: #1890ff;
    margin: 0 15px;
  }

  .remove-file-btn {
    background-color: #ff4d4f;
    color: white;
    border: none;
    padding: 4px 8px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
  }

  .form-actions {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 30px;
  }

  .cancel-btn,
  .submit-btn {
    padding: 10px 24px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
    transition: all 0.3s;
  }

  .cancel-btn {
    background-color: #fff;
    color: #1890ff;
    border: 1px solid #1890ff;
  }

  .cancel-btn:hover {
    background-color: #e6f7ff;
  }

  .submit-btn {
    background-color: #1890ff;
    color: white;
    border: 1px solid #1890ff;
  }

  .submit-btn:hover:not(:disabled) {
    background-color: #40a9ff;
    border-color: #40a9ff;
  }

  .submit-btn:disabled {
    background-color: #bfbfbf;
    border-color: #bfbfbf;
    cursor: not-allowed;
  }

  @media (max-width: 768px) {
    .publish-form-container {
      padding: 20px;
    }

    .form-actions {
      flex-direction: column;
    }

    .cancel-btn,
    .submit-btn {
      width: 100%;
    }
  }
  </style>
